import { 
  ELEMENT_SIZES, 
  VISIBILITY_TYPES, 
  DIAGRAM_TYPES,
  PARTICIPANT_COLORS,
  COLOR_MAP
} from './constants.js'

/**
 * 获取可见性符号
 * @param {string} visibility - 可见性类型
 * @returns {string} 可见性符号
 */
export function getVisibilitySymbol(visibility) {
  switch (visibility) {
    case VISIBILITY_TYPES.PUBLIC: return '+'
    case VISIBILITY_TYPES.PRIVATE: return '-'
    case VISIBILITY_TYPES.PROTECTED: return '#'
    default: return '+'
  }
}

/**
 * 获取元素宽度
 * @param {Object} element - 元素对象
 * @returns {number} 元素宽度
 */
export function getElementWidth(element) {
  // 自适应宽度：针对类/接口/枚举，按标题/属性/方法文本长度动态计算宽度
  if (element && (element.type === 'class' || element.type === 'interface' || element.type === 'enum')) {
    const minWidth = (ELEMENT_SIZES[element.type]?.width) || (ELEMENT_SIZES.default.width)

    const titleFont = '600 14px Inter, Arial'
    const contentFont = '12px Menlo, Consolas, monospace'

    const measure = (text, font) => {
      if (typeof document === 'undefined') {
        // 非浏览环境（兜底估算）：按字符数近似
        const avg = font && font.includes('12px') ? 7 : 8
        return (text || '').length * avg
      }
      if (!window.__umlMeasureCanvas) {
        window.__umlMeasureCanvas = document.createElement('canvas')
      }
      const ctx = window.__umlMeasureCanvas.getContext('2d')
      ctx.font = font
      return ctx.measureText(text || '').width
    }

    // 标题行：interface/enum 显示两行提示+名称，其余仅名称
    let titleLines = []
    if (element.type === 'interface') {
      titleLines = ['«interface»', element.name || '']
    } else if (element.type === 'enum') {
      titleLines = ['«enum»', element.name || '']
    } else {
      titleLines = [element.name || '']
    }
    const titleWidth = Math.max(...titleLines.map(line => measure(line, titleFont)))

    // 内容区：属性/方法
    let contentMax = 0
    if (Array.isArray(element.attributes)) {
      for (const attr of element.attributes) {
        const vis = getVisibilitySymbol(attr?.visibility)
        const text = `${vis} ${attr?.name || ''}: ${attr?.type || ''}`
        contentMax = Math.max(contentMax, measure(text, contentFont))
      }
    }
    if (Array.isArray(element.methods)) {
      for (const m of element.methods) {
        const vis = getVisibilitySymbol(m?.visibility)
        const text = `${vis} ${m?.name || ''}(): ${m?.returnType || ''}`
        contentMax = Math.max(contentMax, measure(text, contentFont))
      }
    }

    // 左右内边距（与绘制时一致的余量，避免贴边）
    const horizontalPadding = 20
    const computed = Math.ceil(Math.max(titleWidth, contentMax) + horizontalPadding)
    return Math.max(minWidth, computed)
  }

  const size = ELEMENT_SIZES[element?.type] || ELEMENT_SIZES.default
  return size.width
}

/**
 * 获取元素高度
 * @param {Object} element - 元素对象
 * @returns {number} 元素高度
 */
export function getElementHeight(element) {
  if (element.type === 'lifeline') {
    return ELEMENT_SIZES.lifeline.height
  }
  
  let baseHeight = 60
  if (element.attributes) baseHeight += element.attributes.length * 15
  if (element.methods) baseHeight += element.methods.length * 15
  return Math.max(baseHeight, 100)
}

/**
 * 获取元素中心点
 * @param {Object} element - 元素对象
 * @returns {Object} 中心点坐标 {x, y}
 */
export function getElementCenter(element) {
  const width = getElementWidth(element)
  const height = getElementHeight(element)
  
  return {
    x: element.x + width / 2,
    y: element.y + height / 2
  }
}

/**
 * 获取元素边界点
 * @param {Object} fromCenter - 起始中心点
 * @param {Object} toCenter - 目标中心点
 * @param {Object} element - 元素对象
 * @param {string} type - 类型 ('source' 或 'target')
 * @returns {Object} 边界点坐标 {x, y}
 */
export function getElementEdgePoint(fromCenter, toCenter, element, type) {
  const width = getElementWidth(element)
  const height = getElementHeight(element)
  
  const left = element.x
  const right = element.x + width
  const top = element.y
  const bottom = element.y + height
  
  const dx = toCenter.x - fromCenter.x
  const dy = toCenter.y - fromCenter.y
  
  if (Math.abs(dx) < 0.1 && Math.abs(dy) < 0.1) {
    return { x: fromCenter.x, y: fromCenter.y }
  }
  
  const length = Math.sqrt(dx * dx + dy * dy)
  const unitDx = dx / length
  const unitDy = dy / length
  
  let intersections = []
  
  if (Math.abs(unitDx) > 0.1) {
    const leftT = (left - fromCenter.x) / unitDx
    const leftY = fromCenter.y + unitDy * leftT
    if (leftY >= top && leftY <= bottom) {
      intersections.push({ x: left, y: leftY, distance: Math.abs(leftT) })
    }
    
    const rightT = (right - fromCenter.x) / unitDx
    const rightY = fromCenter.y + unitDy * rightT
    if (rightY >= top && rightY <= bottom) {
      intersections.push({ x: right, y: rightY, distance: Math.abs(rightT) })
    }
  }
  
  if (Math.abs(unitDy) > 0.1) {
    const topT = (top - fromCenter.y) / unitDy
    const topX = fromCenter.x + unitDx * topT
    if (topX >= left && topX <= right) {
      intersections.push({ x: topX, y: top, distance: Math.abs(topT) })
    }
    
    const bottomT = (bottom - fromCenter.y) / unitDy
    const bottomX = fromCenter.x + unitDx * bottomT
    if (bottomX >= left && bottomX <= right) {
      intersections.push({ x: bottomX, y: bottom, distance: Math.abs(bottomT) })
    }
  }
  
  if (intersections.length > 0) {
    const closest = intersections.reduce((min, current) => 
      current.distance < min.distance ? current : min
    )
    return { x: closest.x, y: closest.y }
  }
  
  return { x: fromCenter.x, y: fromCenter.y }
}

/**
 * 计算点到线段的距离
 * @param {number} px - 点的x坐标
 * @param {number} py - 点的y坐标
 * @param {number} x1 - 线段起点x坐标
 * @param {number} y1 - 线段起点y坐标
 * @param {number} x2 - 线段终点x坐标
 * @param {number} y2 - 线段终点y坐标
 * @returns {number} 距离
 */
export function pointToLineDistance(px, py, x1, y1, x2, y2) {
  const A = px - x1
  const B = py - y1
  const C = x2 - x1
  const D = y2 - y1
  
  const dot = A * C + B * D
  const lenSq = C * C + D * D
  
  if (lenSq === 0) {
    return Math.sqrt(A * A + B * B)
  }
  
  let param = dot / lenSq
  
  let xx, yy
  
  if (param < 0) {
    xx = x1
    yy = y1
  } else if (param > 1) {
    xx = x2
    yy = y2
  } else {
    xx = x1 + param * C
    yy = y1 + param * D
  }
  
  const dx = px - xx
  const dy = py - yy
  
  return Math.sqrt(dx * dx + dy * dy)
}

/**
 * 获取图表类型标题
 * @param {string} diagramType - 图表类型
 * @returns {string} 图表标题
 */
export function getDiagramTypeTitle(diagramType) {
  switch (diagramType) {
    case DIAGRAM_TYPES.CLASS: return '类图'
    case DIAGRAM_TYPES.ACTIVITY: return '活动图'
    case 'data_flow': return '数据流图'
    case DIAGRAM_TYPES.SEQUENCE: return '时序图'
    case DIAGRAM_TYPES.USECASE: return '用例图'
    case DIAGRAM_TYPES.STATE: return '状态图'
    default: return '图'
  }
}

/**
 * 获取关系类型名称
 * @param {string} type - 关系类型
 * @returns {string} 关系类型名称
 */
export function getRelationshipTypeName(type) {
  switch (type) {
    case 'association': return '关联'
    case 'inheritance': return '继承'
    case 'implementation': return '实现'
    case 'composition': return '组合'
    case 'aggregation': return '聚合'
    case 'dependency': return '依赖'
    default: return '关系'
  }
}

/**
 * 获取元素类型名称
 * @param {string} type - 元素类型
 * @returns {string} 元素类型名称
 */
export function getElementTypeName(type) {
  switch (type) {
    case 'class': return '类'
    case 'interface': return '接口'
    case 'relationship': return '关系'
    case 'activity': return '活动'
    case 'lifeline': return '参与者'
    case 'usecase': return '用例'
    case 'state': return '状态'
    case 'enum': return '枚举'
    default: return type
  }
}

/**
 * 获取元素图标
 * @param {string} type - 元素类型
 * @returns {string} 元素图标
 */
export function getElementIcon(type) {
  switch (type) {
    case 'class': return 'C'
    case 'interface': return 'I'
    case 'relationship': return 'R'
    case 'activity': return 'A'
    case 'lifeline': return 'L'
    case 'usecase': return 'U'
    case 'state': return 'S'
    case 'enum': return 'E'
    default: return 'E'
  }
}

/**
 * 获取参与者颜色配置
 * @param {string} participantType - 参与者类型
 * @param {boolean} selected - 是否选中
 * @returns {Object} 颜色配置
 */
export function getParticipantColors(participantType, selected = false) {
  const colors = PARTICIPANT_COLORS[participantType] || PARTICIPANT_COLORS.default
  
  if (selected) {
    return {
      gradient: ['#e6f7ff', '#bae7ff'],
      stroke: '#1890ff',
      icon: colors.icon
    }
  }
  
  return colors
}

/**
 * 获取颜色值
 * @param {string} colorName - 颜色名称
 * @returns {string} 颜色值
 */
export function getColorValue(colorName) {
  return COLOR_MAP[colorName] || colorName
}

/**
 * 生成唯一ID
 * @param {string} prefix - ID前缀
 * @returns {string} 唯一ID
 */
export function generateId(prefix = 'element') {
  return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

/**
 * 深拷贝对象
 * @param {Object} obj - 要拷贝的对象
 * @returns {Object} 拷贝后的对象
 */
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

/**
 * 防抖函数
 * @param {Function} func - 要防抖的函数
 * @param {number} wait - 等待时间
 * @returns {Function} 防抖后的函数
 */
export function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 * @param {Function} func - 要节流的函数
 * @param {number} limit - 限制时间
 * @returns {Function} 节流后的函数
 */
export function throttle(func, limit) {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

